package src.Thirteen;

import javax.imageio.ImageIO;
import javax.swing.*;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;

public class BackgroundJTextField extends JTextField {

    private static final long serialVersionUID = 5810044732894008630L;
    private TexturePaint paint;

    public BackgroundJTextField(File file){
        super();
        try {
            BufferedImage image = ImageIO.read(file);
            Rectangle rectangle = new Rectangle(0,0,image.getWidth(),image.getHeight());
            paint = new TexturePaint(image,rectangle);
            setOpaque(false);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    protected void paintComponent(Graphics g){
        Graphics2D g2 = (Graphics2D) g;
        g2.setPaint(paint);
        g.fillRect(0,0,getWidth(),getHeight());
        super.paintComponent(g);
    }

    public static void main(String[] args) {
        JFrame jFrame = new JFrame();
        JPanel jPanel = new JPanel();
        BackgroundJTextField backgroundJTextField = new BackgroundJTextField(new File("F:\\ideaProject\\demo\\demo\\java\\src\\Thirteen\\1.jpg"));
        backgroundJTextField.setSize(100,100);
        jPanel.add(backgroundJTextField);
        jFrame.add(jPanel);
        jFrame.setSize(500,500);
        jFrame.setVisible(true);
        jFrame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
    }
}
